package com.asen.commons.core.jdbc.handler;

import java.sql.*;

/**
 * Boolean 类型处理器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-02
 */
public class BooleanTypeHandler extends BaseTypeHandler<Boolean> {

    @Override
    public int getSqlType() {
        return Types.TINYINT;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter)
            throws SQLException {
        ps.setBoolean(i, parameter);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getBoolean(columnName);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getBoolean(columnIndex);
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getBoolean(columnIndex);
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Boolean) {
            return (Boolean) value ? "1" : "0";
        }

        if (value instanceof Boolean[]) {
            StringBuilder sb = new StringBuilder(0);
            sb.append("(");
            for (Boolean s : (Boolean[]) value) {
                if (s == null) {
                    continue;
                }
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append(s ? "1" : "0");
            }
            sb.append(")");
            return sb.toString();
        }

        if (value instanceof boolean[]) {
            StringBuilder sb = new StringBuilder(0);
            sb.append("(");
            for (boolean s : (boolean[]) value) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append(s ? "1" : "0");
            }
            sb.append(")");
            return sb.toString();
        }

        return value.toString();
    }

    @Override
    public Boolean getValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Boolean) {
            return (Boolean) value;
        }

        Boolean actualValue = "1".equals(value.toString()) ? Boolean.TRUE : "true".equalsIgnoreCase(value.toString()) ? Boolean.TRUE : Boolean.FALSE;
        return actualValue;
    }
}
